<template>
  <div>
<!--    <img alt="Vue logo" src="../assets/logo.png">-->
<!--    <HelloWorld msg="Welcome to Your Vue.js App"/>-->
    <div style="margin: 10px 0">
      <lay-button type="primary" @click="add">新增</lay-button>
    </div>
    <div style="margin: 10px 0">
      <lay-input v-model="search" placeholder=" 请输入关键字" style="width:30%"></lay-input>
      <lay-button style="margin-left: 10px" type="primary" @click="list">查询</lay-button>
    </div>
    <lay-table :columns="columns" :dataSource="tableData" :even="true" style="width: 100%">
      <template v-slot:operation="{ data }">
        <lay-button size="xs" type="primary" @click="handleEdit(data)">编辑</lay-button>
        <lay-popconfirm content="确认删除吗?" @confirm="handledelete(data.id)">
          <lay-button size="xs" type="danger">删除</lay-button>
        </lay-popconfirm>
      </template>
    </lay-table>
    <!-- 使用简单的模态框替代LayUI Layer，避免复杂的API问题 -->
    <div v-if="dialogVisible" class="modal-overlay" @click.self="dialogVisible = false">
      <div class="modal-content">
        <div class="modal-header">
          <h3>家居信息</h3>
          <button @click="dialogVisible = false" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <lay-form :model="form" ref="layFormRef" label-width="120px">
            <lay-form-item label="家居名">
              <lay-input v-model="form.name" style="width: 70%"></lay-input>
              <div style="color: red;">{{serverValidErrors.name}}</div>
            </lay-form-item>
            <lay-form-item label="厂商">
              <lay-input v-model="form.maker" style="width: 70%"></lay-input>
              <div style="color: red;">{{serverValidErrors.maker}}</div>
            </lay-form-item>
            <lay-form-item label="价格">
              <lay-input v-model="form.price" style="width: 70%"></lay-input>
              <div style="color: red;">{{serverValidErrors.price}}</div>
            </lay-form-item>
            <lay-form-item label="销量">
              <lay-input v-model="form.sales" style="width: 70%"></lay-input>
              <div style="color: red;">{{serverValidErrors.sales}}</div>
            </lay-form-item>
            <lay-form-item label="库存">
              <lay-input v-model="form.stock" style="width: 70%"></lay-input>
              <div style="color: red;">{{serverValidErrors.stock}}</div>
            </lay-form-item>
          </lay-form>
        </div>
        <div class="modal-footer">
          <lay-button @click="dialogVisible = false">取消</lay-button>
          <lay-button type="primary" @click="save">确定</lay-button>
        </div>
      </div>
    </div>

    <div style="margin: 10px 0">
      <lay-page 
        :total="total" 
        :limit="pageSize" 
        :current="currentPage"
        :limits="[3,5,10]"
        show-count
        show-limit
        show-skip
        @change="handlePageChange">
      </lay-page>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src

import request from "@/utils/request";
export default {
  name: 'HomeView',
  components: {
  },
  data() {
    return {
      serverValidErrors:{},
      currentPage:1,
      pageSize:5,
      total:10,
      search:'',
      dialogVisible:false,
      form:{},
      tableData: [
      ],
      columns: [
        {
          title: "ID",
          key: "id",
          sort: "desc"
        },
        {
          title: "家居名",
          key: "name"
        },
        {
          title: "厂家", 
          key: "maker"
        },
        {
          title: "价格",
          key: "price"
        },
        {
          title: "销量",
          key: "sales"
        },
        {
          title: "库存",
          key: "stock"
        },
        {
          title: "操作",
          customSlot: "operation",
          key: "operation",
          width: "180px"
        }
      ],
      rules:{
        name:[
            {required : true , message : "请输入家居名" , trigger : "blur"}
        ],
        maker: [
          {required: true, message: '请输入称制造商', trigger: 'blur'}
        ],price: [
          {required: true, message: '请输入价格', trigger: 'blur'},
          {pattern: /^(([1-9]\d*)|(0))(\.\d+)?$/, message: '请输入数字', trigger: 'blur'}
        ],sales: [
          {required: true, message: '请输入销量', trigger: 'blur'},
          {pattern: /^(([1-9]\d*)|(0))$/, message: '请输入数字', trigger: 'blur'}
        ],stock: [
          {required: true, message: '请输入库存', trigger: 'blur'},
          {pattern: /^(([1-9]\d*)|(0))$/, message: '请输入数字', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.list()
  },
  methods:{
    add(){
      this.dialogVisible = true
      this.form = {}
      if (this.$refs['layFormRef'] != undefined){
        this.$refs['layFormRef'].reset()
      }
      this.serverValidErrors = {}
    },
    save() {
      if(this.form.id){
        request.put("/api/update",this.form).then(res =>{
          if(res.code === 200){
            this.$layer.msg("更新成功", { icon: 1, time: 2000 })
          }else {
            this.$layer.msg("更新失败", { icon: 2, time: 2000 })
          }
          this.dialogVisible = false
          this.list()
        })
      }else {
        // 暂时跳过表单验证，直接提交（LayUI Vue的表单验证API可能不同）
        request.post("/api/save", this.form).then(res => {
          // console.log("res=", res)
          if(res.code === 200){
            this.dialogVisible = false
            this.$layer.msg("添加成功", { icon: 1, time: 2000 })
            this.list()
          }else if(res.code === 400){
            this.serverValidErrors.name = res.extend.errorMsg.name
            this.serverValidErrors.maker = res.extend.errorMsg.maker
            this.serverValidErrors.price = res.extend.errorMsg.price
            this.serverValidErrors.sales = res.extend.errorMsg.sales
            this.serverValidErrors.stock = res.extend.errorMsg.stock
            this.$layer.msg("添加失败", { icon: 2, time: 2000 })
          }
        }).catch(err => {
          console.error("请求失败:", err)
          this.$layer.msg("请求失败", { icon: 2, time: 2000 })
        })

      }
    },
    list(){
      // request.get("/api/furns").then(res =>{
      //   // console.log("res=",res)
      //   this.tableData = res.extend.furnList
      // })
      request.get("/api/furnsByConditionPage", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search:this.search
          }
      }).then(res => {
//绑定 tableData, 显示在表格
        this.tableData = res.extend.pageInfo.list
        this.total = res.extend.pageInfo.total
      })
    },
    handleEdit(row){
      //console.log("row",row)
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true
      // request.get("/api/select/" + row.id).then(res =>{
      //   this.form = res.extend.furn
      // })
      // this.dialogVisible = true
    },
    handledelete(id){
        request.delete("/api/delete/" + id).then(res =>{
          if(res.code === 200){
            this.$layer.msg(res.msg || "删除成功", { icon: 1, time: 2000 })
          }else {
            this.$layer.msg(res.msg || "删除失败", { icon: 2, time: 2000 })
          }
          this.list()
        }).catch(err => {
          console.error("删除失败:", err)
          this.$layer.msg("删除失败", { icon: 2, time: 2000 })
        })
      },
    handlePageChange(obj){
      // LayUI分页组件的事件对象包含 current 和 limit 属性
      if(obj.current !== undefined){
        this.currentPage = obj.current
      }
      if(obj.limit !== undefined){
        this.pageSize = obj.limit
      }
      this.list()
    }
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  max-height: 80%;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
